// 日期格式化
export function parseTime(time, pattern, validTime) {
  if (!time && !validTime) return ''
  if (!time) time = new Date()
  let format = pattern || 'datetime_i'
  if (format === 'date') format = '{y}-{m}-{d}'
  if (format === 'datetime_i') format = '{y}-{m}-{d} {h}:{i}'
  if (format === 'datetime') format = '{y}-{m}-{d} {h}:{i}:{s}'

  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 时间格式转换成中文
export function timeToText(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) return parseTime(time, option)
  return parseTime(time, 'm月d日h时m分')
}

// 计算年龄
export function getAge(birthday) {
  if (!birthday) return 0
  const today = new Date() // 获取当前日期时间
  const birthdate = new Date(birthday) // 将生日字符串转换为日期格式
  let age = today.getFullYear() - birthdate.getFullYear() // 根据年份计算年龄
  if (today < birthdate || today.getMonth() < birthdate.getMonth()) {
    age-- // 如果今天的月份小于生日的月份或者今天的日期小于生日的日期，则年龄需要减1
  }
  return age
}
